package com.winai.launcher.BroadcastReceiver;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.manager.VideoManager;
import com.winai.launcher.manager.VolumeWindow;
import com.winai.launcher.manager.WifiAutoConnectManager;
import com.winai.launcher.override.CountTimer;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.OpenAppUtils;

/**
 * 作者：康少
 * 时间：2020/4/20 0020
 * 说明：系统操作——广播
 */
public class SystemEventReceiver extends BroadcastReceiver {

    public static int mIndex;
    public static boolean muted = false;
    private final String TAG = "SystemEventReceiver";
    private final String action_volume = "com.winai.media.VOLUME_CHANGED_ACTION";//音量键按下
    //    private final String action_volume = "android.media.winside.VOLUME_CHANGED_ACTION";//音量键按下
    private final String ACTION_MUTE = "android.media.STREAM_MUTE_CHANGED_ACTION";//音量改变
    private static final String BROADCAST_ACTION_DISC = "com.cn.customview.permissions.my_broadcast";//播放Engineer视频
    private static final String ACTION_WRONG_WIFI_PSW = "com.android.server.wifi.onWrongPasswordError";//WiFi密码错误
    private static final String SYSTEM_MEDIA_CTRL = "com.android.winside.launcher.system.media.control";//接收systemUI的广播控制媒体播放
    private static final String LAST_USE_ACTIVITY = "com.winai.system.lastUserActivityTime";//用户最后一次操作屏幕广播
//    private static final String LAST_USE_ACTIVITY = "com.android.winside.lastUserActivityTime";//用户最后一次操作屏幕广播

    private static final String ACTION_SYSTEMUI_OPEN_PAGE = "com.systemui.action.aiyishengPage.open";//systemui打开艾益生页面

    private Context mContext;

    private AudioManager mAudioManager;

    public void init(Context mContext) {
        LogUtils.i("注册了按键广播");
        this.mContext = mContext;
        ensureAudioManager();
        mIndex = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BROADCAST_ACTION_DISC);
        filter.addAction(action_volume);
        filter.addAction(ACTION_MUTE);
        filter.addAction(SYSTEM_MEDIA_CTRL);
        filter.addAction(LAST_USE_ACTIVITY);
        filter.addAction(ACTION_SYSTEMUI_OPEN_PAGE);
        mContext.registerReceiver(this, filter);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        LogUtils.i("监听到系统操作广播，intent.getAction() = " + intent.getAction());
        if (intent.getAction() != null) {
            if (intent.getAction().equals(action_volume)) {
                if (BaseUtils.isAPPBroughtToBackground(context, "com.aiyisheng.speaker"
                        , "com.aiyisheng.speaker.main.time.alarm.AlarmPreviewActivity")) {
                    LogUtils.d("拦截艾益生响铃的音量弹窗");
                    return;
                }
                int streamType = intent.getIntExtra("streamType", -1);//3为媒体音量
                int newIndex = intent.getIntExtra("newIndex", -1);//当前音量值
                int oldIndex = intent.getIntExtra("oldIndex", -1);//旧的音量值
                mIndex = newIndex;
                onKeyDown(newIndex, oldIndex);
            } else if (intent.getAction().equals(BROADCAST_ACTION_DISC)) {
                // 不锁屏
                String data = intent.getStringExtra("data");
                //是否正在播放视频
                Constant.isPlayVideo = intent.getBooleanExtra("isPlayVideo", false);
                Log.e(TAG, "收到艾益生广播 艾益生视频是否正在播放，isPlayVideo = " + Constant.isPlayVideo);
                if (data != null) {
                    if (data.equals("startPlayEngineer")) {
                        //取消定时器
                        CountTimer.release();
//                        ScreenProtectConstant.time = ScreenProtectConstant.NEVER;
                    } else if (data.equals("stopPlayEngineer")) {
                        CountTimer.restart(context);
//                        ScreenProtectConstant.time = ScreenProtectConstant.TEN;
                    }
                }
            } else if (intent.getAction().equals(ACTION_WRONG_WIFI_PSW)) {
                //wifi 密码错误
                String ssid = intent.getStringExtra("ssid");
                ToastKs.show(context, "密码错误");
                WifiManager mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                WifiAutoConnectManager wifiAutoConnectManager = WifiAutoConnectManager.newInstance(mWifiManager);
                // 取消保存，忽略网络，忽略WiFi，忘记网络
                wifiAutoConnectManager.removeWifiBySsid(ssid);
                GlobalPublisher.Notify(GlobalPublisher.CHANGE_WIFI, 0);
            } else if (intent.getAction().equals(ACTION_MUTE)) {
                final int stream = intent.getIntExtra("android.media.EXTRA_VOLUME_STREAM_TYPE", -1);
                muted = intent
                        .getBooleanExtra("android.media.EXTRA_STREAM_VOLUME_MUTED", false);
                Log.d("TAG", "onReceive STREAM_MUTE_CHANGED_ACTION stream=" + stream
                        + " muted=" + muted);
                //静音状态stream ==3 改变显示音量图标
                if (stream == 3) {
                    VolumeWindow.getInstance(mContext).show(SystemEventReceiver.mIndex);
                    GlobalPublisher.Notify(GlobalPublisher.CHANGE_VOICE_RECEIVER);
                    // 静音状态变更，暂停/播放音频
//                    if (muted) {
//                        if (VideoManager.getInstance(mContext).isVideoPlaying()) {
//                            VideoManager.getInstance(mContext).pause();
//                        }
//                    } else {
//                        if (VideoManager.getInstance(mContext).isVideoPlaying()) {
//                            VideoManager.getInstance(mContext).resume();
//                        }
//                    }
                }
            } else if (intent.getAction().equals(SYSTEM_MEDIA_CTRL)) {
                //控制媒体播放
                String status = intent.getStringExtra("mediaStatus");//resume、pause、stop、next、last
                if (status == null) {
                    return;
                }
                switch (status) {
                    case "resume":
                        VideoManager.getInstance(mContext).requestFocusResume();
                        break;
                    case "pause":
                        VideoManager.getInstance(mContext).pause();
                        break;
                    case "stop":
                        VideoManager.getInstance(mContext).stop();
                        break;
                    case "next":
                        VideoManager.getInstance(mContext).requestFocusPlayNext();
                        break;
                    case "last":
                        VideoManager.getInstance(mContext).requestFocusPlayLast();
                        break;
                    default:
                        break;
                }
            } else if (intent.getAction().equals(LAST_USE_ACTIVITY)) {
                //用户最后一次操作屏幕
                if (!BaseUtils.isAPPBroughtToBackground(context, "com.qiyi.video.speaker"
                        , "com.qiyi.video.speaker.activity.PlayerActivity"))
                    // 需判断是否正艾益生在播放视频
                    if (Constant.isPlayVideo) {
                        CountTimer.release();
                    } else {
                        CountTimer.restart(mContext, 5 * 1000);
                    }
            } else if (intent.getAction() != null && intent.getAction().equals(ACTION_SYSTEMUI_OPEN_PAGE)) {
                String routerPath = intent.getStringExtra("routerPath");
                OpenAppUtils.startIntentPath(context, routerPath, "");
            }
        }
    }

    private void onKeyDown(int newIndex, int oldIndex) {
        if (oldIndex != newIndex) {
            notifyVolumeChanged();
        }
        changeVolume();
    }

    /**
     * 初始化AudioManager，并展示音量进度条
     */
    private void ensureAudioManager() {
        if (mAudioManager == null) {
            if (mContext != null) {
                mAudioManager = (AudioManager) mContext.getSystemService(Service.AUDIO_SERVICE);
            }
        }
    }

    private void changeVolume() {
        ensureAudioManager();
        if (mAudioManager != null) {
            VolumeWindow.getInstance(mContext).show(SystemEventReceiver.mIndex);
//            if (!muted) {
//                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0);//取消静音
//            }
        }
    }

    private void notifyVolumeChanged() {
        if (BaseUtils.isAPPBroughtToBackground(mContext
                , mContext.getPackageName()
                , mContext.getPackageName() + ".view.set.SetVoiceActivity")) {
            GlobalPublisher.Notify(GlobalPublisher.CHANGE_VOICE_RECEIVER);
        }
    }
}
